// pages/firstvist/firstvist.js
const app = getApp()
const URL = app.globalData.localURL

Page({
  data:{
    userlist: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    roles: ["护工", "老人"],
    roleIndex: 0,
  },

  //进入首页
  welcome: function () {
    setTimeout(function () {
      wx.switchTab({
        url: '../index/index',  //可以改成跳转到自己的界面
        fail: function () {
          console.info("跳转失败")
        }
      }) //延迟时间
    }, 2000)
  },

  //刷新本页
  fresh:function(){
    setTimeout(function () {
      wx.navigateTo({
        url: './firstvist',  //刷新界面
      })
    }, 500)
  },

  //姓名输入
  nameInput(e) {
    let that = this;
    app.globalData.user.name = e.detail.value
  },
  //身份证输入
  numberIdInput(e) {
    let that = this;
    app.globalData.user.id_number = e.detail.value
  },

  //角色选择
  bindRoleChange: function(e) {
    console.log('picker country 发生选择改变，携带值为', e.detail.value);
    this.setData({
        roleIndex: e.detail.value
    }),
    // console.log(parseInt(parseInt(e.detail.value) + parseInt(3)));
    app.globalData.user.role_id = parseInt(parseInt(e.detail.value) + parseInt(3));
  },

  //提交认证信息
  submitRequest: function() {
      let user = app.globalData.user;
      let that = this;
      console.log(user);

      if(!user.id_number || !user.name) {
        wx.showToast({
          title: '信息不能为空',
          image: '/images/warn.png',
          duration: 2000
        }) 
      } else {
        wx.request({
          url: URL+'/user_wechat/addUser',
          method: "POST",
          data: {
            'role_id':user.role_id,
            'name':user.name,
            'session_key':user.session_key,
            'sex':user.gender,
            'age':user.age,
            'phone_number':user.phone_number,
            // 'address':user.address,
            // 'qr_code':user.qr_code,
            'id_number':user.id_number,
            'open_id':user.open_id,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function(data) {
            console.log(data);
            if(data.data > -1) {
              wx.showToast({
                title: '认证成功',
                icon: 'success',
                duration: 2000
              });
              that.welcome();
            }else{
              wx.showToast({
                title: '认证失败！',
                icon: '/images/warn.png',
                duration: 2000
              });
              that.fresh();
            }
          },
          fail: function () {
            console.log("服务器连接故障！")
          }
        })
      }
  },

  //测试：后台是否存在当前用户
  queryRequest: function() {
    let that = this;
    wx.request({
      url: URL +'/user_wechat/selectUserByOpenID',
      method: 'POST',
      data: {
        'open_id':app.globalData.user.open_id,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (req) {console.log()
        console.log("Query: "+req.data)
        if(req.data) {
          app.globalData.user.role_id = req.data.role_id;
          console.log(req.data)
          // 跳转界面
          that.welcome();
        }
        else {
          that.showModal();
        }
      },
      fail: function () {
        console.log("初始化连接失败")
      }
    })
  },

  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(550).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  
  //认证请求
  authorizeRequest: function() {
    if (app.globalData.userInfo && app.globalData.encryptedData && app.globalData.iv) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse && app.globalData.encryptedData && app.globalData.iv) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },

  openRequest: function() {
    //for open-id
    let that = this;
    wx.login({
      success: function (res) {
        app.globalData.code = res.code;
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              app.globalData.encryptedData = res.encryptedData
              app.globalData.iv = res.iv
              wx.request({
                url: URL + '/openID/decodeUserInfo',
                method: "GET",
                header: {
                  "Content-Type": "applciation/json"
                },
                data: { encryptedData: app.globalData.encryptedData, iv: app.globalData.iv, code: app.globalData.code },
                success: function (e) {
                  console.log("Open: "+e.data.userInfo);
                  if (e.data.status == 1) {
                    let userInfos = e.data.userInfo;
                    app.globalData.user.open_id = userInfos.openId;
                    app.globalData.myopenid = userInfos.openId;
                    that.queryRequest();
                  }
                  else {
                    console.log("decode fail...");
                  }
                },
                fail: function () {
                  console.log("与服务器失联...");
                }
              })
            },
            fail: function () {
              console.log("与微信服务器失联...");
            }
          })
        }
      }
    })
  },

  /**
   * 获取微信用户信息
   * @param {*} e 
   */
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    app.globalData.user.nick = e.detail.userInfo.nickName
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.openRequest();
    this.authorizeRequest();
    // this.queryRequest();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
   
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
   
  },

  nameInput: function(e) {
    app.globalData.user.name = e.detail.value;
  },

  ageInput: function (e) {
    app.globalData.user.age = e.detail.value;
  }
})